import Mn from 'backbone.marionette';

/** A Widget for action links
 * Can be initialized in two ways :

    Passing a model with an 'option' attribute describing the Anchor

        new AnchorWidget({model: new Bb.Model({option: {href: 'https://endi.coop', label: 'Link to endi'}})});

    Passing directly the options on widget initialization

        new AnchorWidget({href: 'https://endi.coop', label: 'Link to endi'});
 *
 * It can handle GET actions and popup actions. If you need a POST action (eg:
 * non-idempotent action like deletion), have a look at POSTButtonWidget.
 *
 */
const AnchorWidget = Mn.View.extend({
    tagName: 'div',
    template: require('./templates/AnchorWidget.mustache'),
    ui: {
        anchor: 'a'
    },
    events: {
        'click @ui.anchor': "onClick",
    },
    findOptions(){
        let options;
        const model = this.getOption('model');
        if (model && model.has('option')){
            options = model.get('option');
        } else {
            options = this.options;
        }
        return options;
    },
    templateContext(){

        return {option: this.findOptions()};
    },
    onClick() {
        const options = this.findOptions();
        if (options.popup){
            window.openPopup(options.url);
        }
    }
});


export default AnchorWidget;
